package net.adst.util;

import com.toedter.calendar.JDateChooser;
import net.adst.beans.NaemTec;
import net.adst.beans.OurTecRow;
import net.adst.resources.Constants;
import net.adst.resources.VariableNames;
import net.adst.ui.mainframe.tabs.AdstTabPanel;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import sun.net.ResourceManager;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: alekseipot
 * Date: 12.11.12
 * Time: 9:28
 * To change this template use File | Settings | File Templates.
 */
public class MyUtils {
    public static boolean isDate(HSSFCell cell) {
        if (cell != null) {
            try {
                return cell.getDateCellValue() != null;
            } catch (IllegalStateException e) {
                return false;
            }
        }
        return false;

    }

    /**
     * @param box     is the ComboBox that is about to show its own popup menu
     * @param metrics is used to calculate the width of your combo box's items
     */
    public static void setComboMenuWidth(JComboBox box, FontMetrics metrics) {
        if (box.getItemCount() == 0) {
            return;

        }
        Object comp = box.getUI().getAccessibleChild(box, 0);
        if (!(comp instanceof JPopupMenu)) {
            return;
        }


        //Find which option is the most wide, to set this width as pop up menu's preferred!
        int maxWidth = 0;
        for (int i = 0; i < box.getItemCount(); i++) {
            if (box.getItemAt(i) == null)
                continue;
            int currentWidth = metrics.stringWidth(box.getItemAt(i).toString());
            if (maxWidth < currentWidth)
                maxWidth = currentWidth;
        }
        JPopupMenu popup = (JPopupMenu) comp;
        JScrollPane scrollPane = (JScrollPane) popup.getComponent(0);
        Dimension size = scrollPane.getPreferredSize();
        // +20, as the vertical scroll bar occupy space too.
        size.width = maxWidth + 20;
        scrollPane.setPreferredSize(size);
        scrollPane.setMaximumSize(size);
    }

    public static void removeItem(int tableIndex) {
        try {
            File file = new File(VariableNames.PATH_TO_BD);
            InputStream in = new FileInputStream(file);
            HSSFWorkbook wb = new HSSFWorkbook(in);
            ExcelExtractor extractor = new ExcelExtractor(wb);
            extractor.setFormulasNotResults(false); // Считать формулы
            switch (AdstTabPanel.getIndex()) {
                case 0: {
                    JTable detailsTable = (JTable) DataManager.getObject(VariableNames.UI_NAEM_DETAILED_TABLE);
                    ArrayList<NaemTec> rows = (ArrayList<NaemTec>) DataManager.getObject(VariableNames.TEC_NAEM_USING_ROWS);
                    HSSFSheet sheet = wb.getSheetAt(0);
                    while (detailsTable.getSelectedRows().length > 0) {
                        int selectedRow = detailsTable.getSelectedRows()[0];
                        NaemTec item = rows.get(selectedRow);
                        rows.remove(selectedRow);
                        ((DefaultTableModel) detailsTable.getModel()).removeRow(selectedRow);
                        sheet.removeRow(sheet.getRow(item.getRowInFile()));
                    }
                    FileOutputStream fileOut = new FileOutputStream(VariableNames.PATH_TO_BD);
                    wb.write(fileOut);
                    fileOut.close();
                    JOptionPane.showMessageDialog(null, "Изменение успешно сохранены", "Запись успешно удалена.", JOptionPane.OK_OPTION, new ImageIcon(ResourceManager.class.getResource("/images/success.png")));
                    MainDataBuilder.buildData();
                    break;
                }
                case 1: {
                    JTable detailsTable = (JTable) DataManager.getObject(VariableNames.UI_OUR_DETAILED_TABLE);
                    ArrayList<OurTecRow> rows = (ArrayList<OurTecRow>) DataManager.getObject(VariableNames.TEC_OUR_USING_ROWS);
                    while (detailsTable.getSelectedRows().length > 0) {
                        int selectedRow = detailsTable.getSelectedRows()[0];
                        OurTecRow item = rows.get(selectedRow);
                        rows.remove(selectedRow);
                        HSSFSheet sheet = wb.getSheet(item.getShortName());
                        ((DefaultTableModel) detailsTable.getModel()).removeRow(selectedRow);
                        sheet.removeRow(sheet.getRow(item.getRowInFile()));
                    }
                    FileOutputStream fileOut = new FileOutputStream(VariableNames.PATH_TO_BD);
                    wb.write(fileOut);
                    fileOut.close();
                    JOptionPane.showMessageDialog(null, "Изменение успешно сохранены", "Запись успешно удалена.", JOptionPane.OK_OPTION, new ImageIcon(ResourceManager.class.getResource("/images/success.png")));
                    MainDataBuilder.buildData();
                    break;
                }
            }
        } catch (IOException e1) {
            JOptionPane.showOptionDialog(null, "Нет доступа к базе данных. Она используется другой программой.\n Закройте все программы которые могут использовать ее (скорее всего это excel)", "данные не изменены", JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
        }
    }

    public static void saveChanges() {
        try {
            File file = new File(VariableNames.PATH_TO_BD);
            InputStream in = new FileInputStream(file);
            HSSFWorkbook wb = new HSSFWorkbook(in);
            ExcelExtractor extractor = new ExcelExtractor(wb);
            extractor.setFormulasNotResults(false); // Считать формулы
            HSSFSheet sheetNaem = wb.getSheetAt(0);
            JTable detailsTable = (JTable) DataManager.getObject(VariableNames.UI_NAEM_DETAILED_TABLE);
            ArrayList<NaemTec> rowsNaem = (ArrayList<NaemTec>) DataManager.getObject(VariableNames.TEC_NAEM_USING_ROWS);
            if (rowsNaem != null && rowsNaem.size() > 0) {
                for (NaemTec item : rowsNaem) {
                    HSSFRow row = sheetNaem.getRow(item.getRowInFile());
                    HSSFCell cel1D = row.getCell(0);
                    Calendar dateCal = Calendar.getInstance();
                    dateCal.set(Integer.valueOf(detailsTable.getValueAt(rowsNaem.indexOf(item), 0).toString().substring(6, 10)), Integer.valueOf(detailsTable.getValueAt(rowsNaem.indexOf(item), 0).toString().substring(3, 5)) - 1, Integer.valueOf(detailsTable.getValueAt(rowsNaem.indexOf(item), 0).toString().substring(0, 2)));
                    cel1D.setCellValue(dateCal.getTime());
                    CellStyle dateCellStyle = wb.createCellStyle();
                    dateCellStyle.setDataFormat(wb.createDataFormat().getFormat("dd.MM.yyyy"));
                    dateCellStyle.setBorderBottom(CellStyle.BORDER_THIN);
                    dateCellStyle.setBorderLeft(CellStyle.BORDER_THIN);
                    dateCellStyle.setBorderRight(CellStyle.BORDER_THIN);
                    dateCellStyle.setBorderTop(CellStyle.BORDER_THIN);
                    if (item.getPaidNam()) {
                        dateCellStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
                        dateCellStyle.setFillBackgroundColor(HSSFColor.YELLOW.index);
                    } else {
                        dateCellStyle.setFillForegroundColor(HSSFColor.WHITE.index);
                        dateCellStyle.setFillBackgroundColor(HSSFColor.WHITE.index);
                    }
                    cel1D.setCellStyle(dateCellStyle);
                    for (int j = 1; j < Constants.NAEM_НEADER.length - 1; j++) {
                        HSSFCell cel1 = row.getCell(j);
//                        if (j == 6 || j == 9 || j == 10 || j == 12 || j == 13 || j == 14 || j == 15 || j == 17 || j == 18) {
//                            cel1.setCellType(Cell.CELL_TYPE_NUMERIC);
//                            cel1.setCellValue(!(String.valueOf(detailsTable.getValueAt(rowsNaem.indexOf(item), j))).isEmpty() ? Double.valueOf(detailsTable.getValueAt(rowsNaem.indexOf(item), j).toString()) : new Double(0));
//                        } else {
                        cel1.setCellValue(detailsTable.getValueAt(rowsNaem.indexOf(item), j) != null ? detailsTable.getValueAt(rowsNaem.indexOf(item), j).toString() : "");
//                        }
                        if (j == 11) {
                            CellStyle cell1CellStyle = wb.createCellStyle();
                            cell1CellStyle.setBorderBottom(CellStyle.BORDER_THIN);
                            cell1CellStyle.setBorderLeft(CellStyle.BORDER_THIN);
                            cell1CellStyle.setBorderRight(CellStyle.BORDER_THIN);
                            cell1CellStyle.setBorderTop(CellStyle.BORDER_THIN);

                            switch (item.getMoneyIn()) {
                                case 0:
                                    cell1CellStyle.setFillForegroundColor(HSSFColor.WHITE.index);
                                    cell1CellStyle.setFillBackgroundColor(HSSFColor.WHITE.index);
                                    break;
                                case 1:
                                    cell1CellStyle.setFillForegroundColor(HSSFColor.VIOLET.index);
                                    cell1CellStyle.setFillBackgroundColor(HSSFColor.VIOLET.index);
                                    break;
                                case 2:
                                    cell1CellStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
                                    cell1CellStyle.setFillBackgroundColor(HSSFColor.YELLOW.index);
                                    break;
                            }
                            cel1.setCellStyle(cell1CellStyle);
                        }
                    }
                    String[] comment = item.getComment().split("\n");
                    for (int k = 0; k < comment.length; k++) {
                        HSSFCell cell = row.createCell(Constants.NAEM_НEADER.length + k - 1);
                        cell.setCellValue(comment[k]);
                    }
                    for (int k = Constants.NAEM_НEADER.length + comment.length - 1; k < Constants.NAEM_НEADER.length + 15 + comment.length; k++) {
                        if (row.getCell(k) != null) {
                            row.getCell(k).setCellValue("");
                        }
                    }

                }
            }
            JTable detailsTableOur = (JTable) DataManager.getObject(VariableNames.UI_OUR_DETAILED_TABLE);
            ArrayList<OurTecRow> rowsOur = (ArrayList<OurTecRow>) DataManager.getObject(VariableNames.TEC_OUR_USING_ROWS);
            if (rowsOur != null && rowsOur.size() > 0) {
                for (int i = 0; i < rowsOur.size(); i++) {
                    OurTecRow item = rowsOur.get(i);
                    HSSFSheet sheet = wb.getSheet(item.getShortName());
                    HSSFRow row = sheet.getRow(item.getRowInFile());
                    HSSFCell cel1D = row.getCell(0);
                    Calendar dateCal = Calendar.getInstance();
                    dateCal.set(Integer.valueOf(detailsTableOur.getValueAt(i, 0).toString().substring(6, 10)), Integer.valueOf(detailsTableOur.getValueAt(i, 0).toString().substring(3, 5)) - 1, Integer.valueOf(detailsTableOur.getValueAt(i, 0).toString().substring(0, 2)));
                    cel1D.setCellValue(dateCal.getTime());
                    CellStyle dateCellStyle = wb.createCellStyle();
                    dateCellStyle.setDataFormat(wb.createDataFormat().getFormat("dd.MM.yyyy"));
                    dateCellStyle.setBorderBottom(CellStyle.BORDER_THIN);
                    dateCellStyle.setBorderLeft(CellStyle.BORDER_THIN);
                    dateCellStyle.setBorderRight(CellStyle.BORDER_THIN);
                    dateCellStyle.setBorderTop(CellStyle.BORDER_THIN);
                    if (((ArrayList<OurTecRow>) DataManager.getObject(VariableNames.TEC_OUR_USING_ROWS)).get(i).getPaidFor()) {
                        dateCellStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
                        dateCellStyle.setFillBackgroundColor(HSSFColor.YELLOW.index);
                    } else {
                        dateCellStyle.setFillForegroundColor(HSSFColor.WHITE.index);
                        dateCellStyle.setFillBackgroundColor(HSSFColor.WHITE.index);
                    }
                    cel1D.setCellStyle(dateCellStyle);

                    for (int j = 2; j < Constants.OUR_НEADER.length - 1; j++) {
                        HSSFCell cel1 = row.getCell(j - 1);
                        if (cel1 != null) {
                            if (j == 5 || j == 6 || j == 7 || j == 8 || j == 12 || j == 13 || j == 14 || j == 15 || j == 17 || j == 18 || j == 19) {
                                cel1.setCellType(Cell.CELL_TYPE_NUMERIC);
                                cel1.setCellValue(!(String.valueOf(detailsTableOur.getValueAt(i, j))).isEmpty() ? Double.valueOf(detailsTableOur.getValueAt(i, j).toString()) : new Double(0));
                            } else {
                                cel1.setCellValue(detailsTableOur.getValueAt(i, j) != null ? detailsTableOur.getValueAt(i, j).toString() : "");
                            }

                        } else {
                            cel1 = row.createCell(j - 1);
                            if (j == 5 || j == 6 || j == 7 || j == 8 || j == 12 || j == 13 || j == 14 || j == 15 || j == 17 || j == 18 || j == 19) {
                                cel1.setCellType(Cell.CELL_TYPE_NUMERIC);
                                cel1.setCellValue(!(String.valueOf(detailsTableOur.getValueAt(i, j))).isEmpty() ? Double.valueOf(detailsTableOur.getValueAt(i, j).toString()) : new Double(0));
                            } else {
                                cel1.setCellValue(detailsTableOur.getValueAt(i, j) != null ? detailsTableOur.getValueAt(i, j).toString() : "");
                            }
                        }
                    }
                    String[] comment = item.getComment().split("\n");
                    for (int k = 0; k < comment.length; k++) {
                        HSSFCell cell = row.createCell(Constants.OUR_НEADER.length + k - 2);
                        cell.setCellValue(comment[k]);
                    }
                    for (int k = Constants.OUR_НEADER.length + comment.length - 2; k < Constants.OUR_НEADER.length + 15 + comment.length; k++) {
                        if (row.getCell(k) != null) {
                            row.getCell(k).setCellValue("");
                        }
                    }

                }
            }

            FileOutputStream fileOut = new FileOutputStream(VariableNames.PATH_TO_BD);
            wb.write(fileOut);
            fileOut.close();
            JOptionPane.showMessageDialog(null, "Изменение успешно сохранены", "Запись успешно удалена.", JOptionPane.OK_OPTION, new ImageIcon(ResourceManager.class.getResource("/images/success.png")));
            MainDataBuilder.buildData();
//            Searcher.searchOur();
        } catch (IOException e1) {
            JOptionPane.showOptionDialog(null, "Нет доступа к базе данных. Она используется другой программой.\n Закройте все программы которые могут использовать ее (скорее всего это excel)", "данные не изменены", JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
            ((JButton) DataManager.getObject(VariableNames.UI_TOP_PANEL_SAVE_BUTTON)).setEnabled(true);
        }
    }

    public static HSSFRow getFirstEmptyRow(HSSFSheet sheet) {
        HSSFRow row = null;
        for (int i = 3; i < sheet.getLastRowNum() + 2; i++) {
            if (sheet.getRow(i) == null) {// && MyUtils.isDate(sheet.getRow(i - 1).getCell(0))) {
                row = sheet.createRow(i);
                break;
            }
        }
        if (row == null) {
            row = sheet.createRow(sheet.getLastRowNum() + 1);
        }
        return row;
    }

    public static Integer getAbcNum(char chr) {
        String str = String.valueOf(chr);
        String[] abc = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
        for (int i = 0; i < abc.length; i++) {
            if (abc[i].equals(str)) {
                return i;
            }
        }
        return -1;
    }

    public static boolean checkDates(Date date) {
        Calendar dtFrom = (Calendar) ((JDateChooser) DataManager.getObject(VariableNames.CALENDAR_DATE_FROM)).getCalendar().clone();
        Calendar dtTo = (Calendar) ((JDateChooser) DataManager.getObject(VariableNames.CALENDAR_DATE_TO)).getCalendar().clone();
        return compareDate(date, dtFrom.getTime()) && compareDate(dtTo.getTime(), date);
    }

    /**
     * return true if(date>=dateFrom)
     */
    public static boolean compareDate(Date date, Date dtFrom) {
        String dateStr = new SimpleDateFormat("dd.MM.yyyy").format(date);
        String dateFrom = new SimpleDateFormat("dd.MM.yyyy").format(dtFrom);
        double dayFrom = Double.valueOf(dateFrom.substring(0, 2));
        double monthFrom = Double.valueOf(dateFrom.substring(3, 5));
        double yearFrom = Double.valueOf(dateFrom.substring(6, 10));
        double dayDate = Double.valueOf(dateStr.substring(0, 2));
        double monthDate = Double.valueOf(dateStr.substring(3, 5));
        double yearDate = Double.valueOf(dateStr.substring(6, 10));
        if (yearDate >= yearFrom) {
            if (yearDate == yearFrom) {
                if (monthDate >= monthFrom) {
                    if (monthDate == monthFrom) {
                        if (dayDate >= dayFrom) {
                            return true;
                        } else {
                            return false;
                        }
                    } else {
                        return true;
                    }
                } else {
                    return false;
                }
            } else {
                return true;
            }
        } else {
            return false;
        }
    }


    public static boolean isDouble(String arg) {
        try {
            if (!arg.isEmpty()) {
                Double.valueOf(arg);
            }
            return true;
        } catch (IllegalArgumentException ex) {
            return false;
        }
    }
}
